package com.freewater.javabase.demo.jmx.custommbean;

import javax.management.*;
import java.lang.management.ManagementFactory;

/**
 * java -Dcom.sun.management.jmxremote=true \  # 开启远程访问
 * -Dcom.sun.management.jmxremote.port=8398 \		# 自定义 JMX 端口
 * -Dcom.sun.management.jmxremote.ssl=false \		# 是否使用 SSL 协议，生产环境一定要开启
 * -Dcom.sun.management.jmxremote.authenticate=false \ # 是否需要认证，生产环境一定要开启
 * -Djava.rmi.server.hostname=127.0.0.1 YourClass.java # 当前机器 ip
 **/

public class MyMemoryManagement {
    public static void main(String[] args)
            throws MalformedObjectNameException,
            NotCompliantMBeanException,
            InstanceAlreadyExistsException,
            MBeanRegistrationException,
            InterruptedException {
        // 获取 MBean Server
        MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer();
        MyMemory myMemory = new MyMemory();
        myMemory.setTotal(100L);
        myMemory.setUsed(20L);
        // 注册
        ObjectName objectName = new ObjectName("com.freewater.jmx:type=myMemory");
        platformMBeanServer.registerMBean(myMemory, objectName);

        while (true) {
            // 防止进行退出
            Thread.sleep(3000);
            System.out.println(myMemory.doMemoryInfo());
        }
    }
}
